{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2024-04-04T15:34:13.393537600Z",
     "start_time": "2024-04-04T15:34:11.220348700Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-0.773684210526435\n",
      "True\n",
      "[0.9 0.9 0.1]\n"
     ]
    }
   ],
   "source": [
    "# coding=utf-8\n",
    "from scipy.optimize import minimize\n",
    "import numpy as np\n",
    " \n",
    "# demo 2\n",
    "#计算  (2+x1)/(1+x2) - 3*x1+4*x3 的最小值  x1,x2,x3的范围都在0.1到0.9 之间\n",
    "def fun(args):\n",
    "    a,b,c,d=args\n",
    "    v=lambda x: (a+x[0])/(b+x[1]) -c*x[0]+d*x[2]\n",
    "    return v\n",
    "def con(args):\n",
    "    # 约束条件 分为eq 和ineq\n",
    "    #eq表示 函数结果等于0 ； ineq 表示 表达式大于等于0  \n",
    "    x1min, x1max, x2min, x2max,x3min,x3max = args\n",
    "    cons = ({'type': 'ineq', 'fun': lambda x: x[0] - x1min},\\\n",
    "              {'type': 'ineq', 'fun': lambda x: -x[0] + x1max},\\\n",
    "             {'type': 'ineq', 'fun': lambda x: x[1] - x2min},\\\n",
    "                {'type': 'ineq', 'fun': lambda x: -x[1] + x2max},\\\n",
    "            {'type': 'ineq', 'fun': lambda x: x[2] - x3min},\\\n",
    "             {'type': 'ineq', 'fun': lambda x: -x[2] + x3max})\n",
    "    return cons\n",
    " \n",
    "if __name__ == \"__main__\":\n",
    "    #定义常量值\n",
    "    args = (2,1,3,4)  #a,b,c,d\n",
    "    #设置参数范围/约束条件\n",
    "    args1 = (0.1,0.9,0.1, 0.9,0.1,0.9)  #x1min, x1max, x2min, x2max\n",
    "    cons = con(args1)\n",
    "    #设置初始猜测值  \n",
    "    x0 = np.asarray((0.5,0.5,0.5))\n",
    "    \n",
    "    res = minimize(fun(args), x0, method='SLSQP',constraints=cons)\n",
    "    print(res.fun)\n",
    "    print(res.success)\n",
    "    print(res.x)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
